// axios 基础配置
import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/useUserStore'

// 创建axios实例
const http = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000,
})

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    const UserStore = useUserStore()
    if (UserStore.userStore.token) {
      config.headers.Authorization = `Bearer ${UserStore.userStore.token}`
    }
    return config
  },
  (e) => Promise.reject(e)
)

// axios响应式拦截器
http.interceptors.response.use(
  (res) => res.data,
  (e) => {
    ElMessage({ type: 'error', message: e.response.data.message })
    if (e.response.status === 401) {
      localStorage.clear('user')
      router.replace('/login')
    }
    return Promise.reject(e)
  }
)

export default http
